<?php

namespace app\queue\stomp;

use think\Hook;
use Webman\Stomp\Client;
use app\queue\BaseConsumer;
use common\model\TaskModel;
use common\model\UserModel;
use common\model\EntityModel;
use common\service\TaskService;
use common\service\UserService;
use common\service\EntityService;
use common\service\OptionsService;
use common\model\ProjectMemberModel;

/**
 * 任务废除/启用 发送小助手消息
 */
class EntityCloseOperateSendMessageConsumer extends BaseConsumer
{

    // 要消费的队列名
    public $queue = 'entity_close_operate_async_send_producer_message';

    // 连接名，对应 config/redis_queue.php 里的连接`
    public $connection = 'default';


    /**
     * @param $data
     * @return void
     */
    public function doConsume($data)
    {

        $hookData = [
            'type' => 'entity_deprecated',
            'data' => $data,
        ];
        Hook::listen('entity_change_after', $hookData);

        return;
        try {
            $enable = $data['operate'] === 'Ena';
            $entity = model(EntityModel::class)->find($data['entity_id']);
            if (empty($entity)) {
                return;
            }
            $entityScoped = EntityService::getInstance()->getEntityScoped($entity);
            if (empty($entityScoped)) {
                return;
            }

            $queryFields = [
                'task.id',
                'task.name',
                'task.executor',
                'task.tenant_id',
                'task.project_id',
                'task.assignee_producer',
                'task.department_id',
                'task.entity_module_id',

                'entity.id',
                'entity.name',
                'entity.initial_episode_code',
                'entity.showings_number',
            ];
            $relatePeopleTasks = model(TaskModel::class)
                ->join('entity on entity.id = task.entity_id')
                ->where(['entity.id' => ['IN', array_column($entityScoped, 'id')]])
                ->field(build_complex_query_fields($queryFields, '__'))
                ->select();
            if (empty($relatePeopleTasks)) {
                return;
            }
            // 抽取数据
            $userIdList = [];
            $projectIdList = [];
            $departmentIdList = [];
            $tenantIdList = [];

            foreach ($relatePeopleTasks as &$relatePeopleTask) {
                $relatePeopleTask = separate_complex_query_data($relatePeopleTask, '__');
                $userIdList[$relatePeopleTask['task']['executor']] = $relatePeopleTask['task']['executor'];
                $userIdList[$relatePeopleTask['task']['assignee_producer']] = $relatePeopleTask['task']['assignee_producer'];
                $projectIdList[$relatePeopleTask['task']['project_id']] = $relatePeopleTask['task']['project_id'];
                $departmentIdList[$relatePeopleTask['task']['department_id']] = $relatePeopleTask['task']['department_id'];
                $tenantIdList[$relatePeopleTask['task']['tenant_id']] = $relatePeopleTask['task']['tenant_id'];
            }
            unset($departmentIdList[0], $tenantIdList[0], $projectIdList[0]);

            // 项目生产制片查询 组装项目生产制片map
            $projectMemberList = model(ProjectMemberModel::class)
                ->where([
                    'project_id' => ['IN', implode(',', $projectIdList)],
                    'role_code' => TaskService::EXECUTIVE_PRODUCER_CODE,
                ])
                ->field('project_id,user_id')
                ->group('project_id,user_id')
                ->select();
            $userIdList = array_merge($userIdList, array_column($projectMemberList, 'user_id', 'user_id'));
            unset($userIdList[0]);
            // 根据上面的已有user_id 查询当前系统userMap
            $userList = [];
            if (!empty($userIdList)) {
                $userList = model(UserModel::class)->where(['id' => ['IN', implode(',', $userIdList)]])->field('id,name,union_id')->select();
                $userList = array_column($userList, null, 'id');
            }

            // 根据部门id查询组长 组装部门组长map
            if (!empty($departmentIdList)) {
                $filter = [
                    'tenant_id' => ['-in', implode(',', $tenantIdList)],
                    'department_id' => ['-in', implode(',', $departmentIdList)],
                    'role_code' => TaskService::HEADMAN_CODE,
                ];
                $userDepartmentMap = UserService::getInstance()->getDepartmentSaasUserMap($filter);
                foreach ($userDepartmentMap as $departmentUserList) {
                    foreach ($departmentUserList as $departmentUser) {
                        $userList[$departmentUser['id']] = $departmentUser;
                    }
                }
            }
            if (empty($userList)) {
                return;
            }

            unset($relatePeopleTask);
            $taskName = '【' . $entity['initial_episode_code'] . '/' . $entity['showings_number'] . '/' . $entity['name'] . '】';
            if ($enable) {
                $noteText = '废除的任务' . $taskName . '被启用了';
            } else {
                $noteText = '任务' . $taskName . '被废除';
            }
            $templateId = OptionsService::getInstance()->getEntityTaskRemindCommonTemplateId();
            $notifyParam = [
                'first' => '废除任务通知',
                'note_text' => $noteText,
                'remark' => "请及时查看",
                'tenant_id' => $entity['tenant_id'],
                'project_id' => $entity['project_id'],
                'entity_id' => $entity['id'],
                'module_code' => in_array(module_by_id($entity['module_id'])['code'], ['design', 'level', 'asset']) ? 'design' : 'storyboard',
                'message_key' => 'entity_close_operation',
            ];

            $unionList = array_column($userList, 'union_id');
            Client::send('batch_receiver_send_notify_message_v2', build_queue_data_with_xu([
                "param" => $notifyParam,
                'receiver' => $unionList,
                'template_id' => $templateId,
                'content_type' => 'card_message',
                'notice_type' => 'task_remind',
                'is_popup' => 1,
                'message_key' => $notifyParam['message_key'],
            ]));

        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }
}
